const express = require('express');
const router = express.Router();
const sys_user = require('../../../models/sys_user');
const crypto = require('crypto');
const {generate19DigitId}=require("../../../utils/idUtils")
const {encryptPassword,generateSalt}=require("../../../utils/passwordUtils");
const sys_user_role = require('../../../models/sys_user_role');

router.post('/sys/user/reg', async (req, res) => {
    try {
        const { userName, realName, password, identity } = req.body;
        
        // 参数验证
        if (!userName || !realName || !password || !identity) {
            return res.status(400).json({
                msg: "用户名、真实姓名、密码和身份不能为空",
                code: 400,
                success: false
            });
        }

        // 检查用户名是否已存在
        const existingUser = await sys_user.findUserByUsername(userName);
        if (existingUser) {
            return res.status(400).json({
                msg: "用户名已存在",
                code: 400,
                success: false
            });
        }

        // 角色验证
        const roleIds = await sys_user.mapRoleNameToId(identity);
        if (roleIds === 'null') {
            return res.status(400).json({
                msg: "角色名不存在",
                code: 400,
                success: false
            });
        }
        
        // 生成盐值和加密密码
        const salt = generateSalt();
        const encryptedPassword = encryptPassword(password, salt);
        
        // 生成用户ID
        const userId = generate19DigitId();
        
        // 获取当前时间
        const currentTime = new Date();
        
        // 使用 insertUser 方法插入用户数据到sys_user表中
        const userData = {
            id: userId,
            user_name: userName,
            real_name: realName,
            password: encryptedPassword,
            salt: salt,
            role_ids: roleIds,
            state : 1, // 在线状态
            data_flag: 0, // 账户正常状态
            create_time: currentTime,
            update_time: currentTime,
            last_active_time: currentTime
        };
        
        const insertResult = await sys_user.insertUser(userData);
        if (!insertResult) {
            return res.status(500).json({
                msg: "注册用户时出错",
                code: 500,
                success: false
            });
        }
        
        //将用户数据插入到sys_user_role表中
        const userRoleData = {
            id: generate19DigitId(),
            user_id: userId,
            role_id: roleIds,
        };

        // 插入用户角色关系到sys_user_role表中
        const insertUserRoleResult = await sys_user_role.addUserRole(userId, roleIds);
        
        // 使用JWT加密生成token
        const jwt = require('jsonwebtoken');
        const token = jwt.sign({ 
            userId: userId, 
            username: userName,
            roles: [roleIds],
        }, 'secret-key', { expiresIn: '24h' });

        return res.json({
            "msg": "注册成功！",
            "code": 0,
            "data": {
                "id": userId,
                "userName": userName,
                "realName": realName,
                "roleIds": roleIds,
                "createTime": currentTime,
                "updateTime": currentTime,
                "roles": [roleIds],
                "token": token
            },
            "success": true
        });
    } catch (error) {
        console.error("注册用户时出错:", error);
        return res.status(500).json({
            msg: "服务器内部错误",
            code: 500,
            success: false
        });
    }
});

module.exports = router;